package cn.skcks.shirospringboot.config;

import cn.skcks.shirospringboot.pojo.User;
import cn.skcks.shirospringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

// 自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
	@Autowired
	UserService userService;

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行授权方法");

		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

		User user = (User) principals.getPrimaryPrincipal();
		if(user.getName().equals("张三")){
			// 授予权限
			authorizationInfo.addStringPermission("user:add");
		}

		return authorizationInfo;
	}

	// 认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行认证方法");

		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

		// 连接真实数据库
		User user = userService.selectUserByName(usernamePasswordToken.getUsername());

		if (user == null){
			return null;
		}

		// 密码认证
		return new SimpleAuthenticationInfo(user,user.getPwd(),"");
	}
}